/**
 * 注册登录请求
 * */
const {
    express,
    db_mysql,
    errorData,
    addPWD,
    strLen,
    strLenHex,
    host,
    port
} = require('./common-req.js')
const router = express.Router();
// 验证码存放÷
let list = []
/**
 * 登录请求
 * */
router.post('/login', (req, res) => {
    const phone = req.body.phone;
    const password = req.body.password;
    let sql = 'select * from users where phone=? and password=?';
    let sqlArr = [phone, password];
    db_mysql.select(sql, sqlArr, results => {
        if (results && results.length > 0) {
            var resData = {
                data: {},
                status: 0,
                msg: '登录成功'
            }
            resData.data = {
                phone: results[0].phone,
                username: results[0].username,
                src: results[0].src,
                token: addPWD(results[0].phone, results[0].token)
            }
            res.send(resData);
        } else {
            errorData.msg = '登录失败，账号或密码错误';
            res.send(errorData);
        }
    })
})

/**
 * 注册请求
 * */
router.post('/register', (req, res) => {
    const phone = req.body.phone;
    const password = req.body.password;
    const userName = req.body.userName;
    const token = strLen();
    const verifiCode = req.body.verifiCode;
    const src = `${host}:${port}/plantknow/public/images/44.jpg`
    let codeStatus = false; // 验证码是否正确
    for(var k in list) {
        if(list[k].phone === phone) {
            if(list[k].code === verifiCode) {
                codeStatus = true;
                if(list[k].timer) {
                    clearTimeout(list[k].timer);
                }
                list.splice(k, 1)
                break;
            }
        }
    }
    let sql = 'insert into users(phone, password, username, src, token) values(?, ?, ?, ?, ?)';
    let isExitSql = 'select * from users where phone=?';
    let sqlArr = [phone, password, userName, src, token];
    if(codeStatus) {
        db_mysql.select(isExitSql, phone, exitRes => {
            if(exitRes && exitRes.length > 0) {
                errorData.msg = '该用户已注册';
                errorData.code = 200;
                res.send(errorData);
            } else {
                db_mysql.insert(sql, sqlArr, results => {
                    if (results === true) {
                        var resData = {
                            data: null,
                            status: 0,
                            msg: '注册成功'
                        }
                        resData.data = {
                            phone: phone,
                            password: password
                            
                        }
                        res.send(resData);
                    } else {
                        errorData.msg = '注册失败';
                        res.send(errorData);
                    }
                })
            }
        })
    } else {
        errorData.msg = '验证码错误';
        res.send(errorData);
    }
})

/**
 * 获取短信验证码
 * */
router.get('/sms/:phone?', (req, res) => {
    const phone = req.params.phone;
    if(!phone) {
        return;
    }
    const Core = require('@alicloud/pop-core');
    
    var client = new Core({
      accessKeyId: 'LTAI5tALmG4eVQRtkjKKiKnK',
      accessKeySecret: 'Nq2xk5L4N8rFmY3I7mlIKYinaGmcE2',
      endpoint: 'https://dysmsapi.aliyuncs.com',
      apiVersion: '2017-05-25'
    });
    let randomCode = strLenHex();
    let num = Math.floor(Math.random() * 10);
    let code = {
        code: randomCode.substr(num, 6)
    }
    let obj = {
        phone: phone,
        code: randomCode.substr(num, 6),
        timer: null
    }
    list.push(obj);
    let len = list.length - 1;
    obj.timer = setTimeout(() => {
        list.splice(len, 1);
    }, 300000)
    var params = {
      "PhoneNumbers": phone,
      "SignName": "个人网站hr",
      "TemplateCode": "SMS_215350744",
      "TemplateParam": JSON.stringify(code)
    }
    
    var requestOption = {
      method: 'POST'
    };
    client.request('SendSms', params, requestOption).then((result) => {
      console.log(JSON.stringify(result));
      if(result.Code === 'OK') {
          res.send({
              data: null,
              msg: '验证码已发送,注意接收',
              status: 0,
              code: 200
          })
      } else {
          errorData.msg = '获取验证码失败，请重新获取'
          res.send(errorData)
      }
    }, (ex) => {
      console.log(ex);
    })
})

module.exports = router;
